#include "stdafx.h"

#include "BoneSystem.h"




BoneSystem::BoneSystem()
:	PositionalObject(),
	m_bShowBones(true)
{
	
}



BoneSystem::~BoneSystem()
{
	m_bones.clear();
}



//////////////////////////////////////////////////////////////////////////
//void BoneSystem::AddBone(BoneSystem::Bone* pbone)
//{
//	if(pbone==0)
//		return;
//	m_bones.push_back(pbone);
//}
void BoneSystem::AddBone(const Bone& pbone)
{
	m_bones.push_back(pbone);
}


/*
 *	return a pointer of the bone with the specified index
 */
BoneSystem::Bone* BoneSystem::GetBone(int index)
{
	if( (index<0) || (index>=BoneCount()))
		return 0;
	//return m_bones[index];
	return &m_bones[index];
}


/*
 *	return a pointer of the bone that is parent of the bone with the 
 *	specified index
 */
BoneSystem::Bone* BoneSystem::GetBoneParent(int index)
{
	if( (index<0) || (index>=BoneCount()))
		return 0;
	Bone* pbone = &m_bones[index];
	if(pbone->mParentIndex==-1)
		return NULL;
	else
		return &m_bones[pbone->mParentIndex];
}

//////////////////////////////////////////////////////////////////////////
void BoneSystem::DropBone(int index)
{
	if( (index<0) || (index>=BoneCount()))
		return;

	//delete m_bones[index];
	m_bones.erase(m_bones.begin()+index, m_bones.begin()+index+1);
}


//////////////////////////////////////////////////////////////////////////
void BoneSystem::DropAllBones()
{
	/*for (BoneIter iter = BonesBegin();
		 iter != BonesEnd();
		 iter++)
	{
		delete *iter;
	}*/
	m_bones.clear();
}

//////////////////////////////////////////////////////////////////////////
void BoneSystem::Draw()
{
	PositionalObject::Draw();

	if (m_bShowBones)
	{
		glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
		glDepthFunc( GL_ALWAYS );
		glDisable( GL_LIGHTING );
		glDepthRange( 0.0, 0.0 );
		glColor3f( 1.0, 0.5, 0.5 );
		glBegin( GL_LINE_STRIP );
		{
			Quaternion curOrient;
			Vector3 curEnd;	// initially zero vector

			glVertex3(curEnd);
			for (int b=0; b<BoneCount(); b++)
			{
				Bone* pbone = GetBone(b);
				curOrient *= pbone->mRotation;
				Vector3 localEnd(0.0,0.0,pbone->mLength);
				curOrient.RotateVector(localEnd);
				curEnd += localEnd;
				glVertex3(curEnd);
			}
		}
		glEnd();

		glPopAttrib();
	}

}